﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using NetDon.OA.Data.DaoClasses;
using NetDon.OA.Data.HelperClasses;
using NetDon.Utilities;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace NetDon.OA.Business.Sequentials
{

    public class OrderCodeContext
    {
        public string CustomerCode { get; set; }
    }

    public class CustomerOrderCodeSequential : SequentialGenerator
    {
        private DateTime previouseDate;
        private int previouseSequential;
        #region Overrides of SequentialGenerator

        protected override string InitializeValue(object context)
        {
            var c = context as OrderCodeContext;
            if (c == null)
            {
                throw new ArgumentException("Invalid context type.", "context");
            }
            previouseDate = DateTime.Today;
            var fields = new EntityFields(1);
            fields[0] = IssuingOrderFields.OrderCode.SetExpression(
                new DbFunctionCall("SubString({0},{1},{2})", new object[]{ IssuingOrderFields.OrderCode, c.CustomerCode.Length+5, 4 })).SetAggregateFunction(AggregateFunction.Max);
            object maxOrderCode = new TypedListDAO().GetScalar(fields, null, IssuingOrderFields.OrderCode % ("____" + DateTime.Today.ToString("yyMMdd") + "____"), null, null);
            previouseSequential = maxOrderCode == DBNull.Value ? 0 : int.Parse(maxOrderCode.ToString(), NumberStyles.HexNumber);
            return string.Empty;
        }

        protected override string NextValue(object context)
        {
            Assertion.ArgumentNotNull(context, "context");
            var c = context as OrderCodeContext;
            if (c == null)
            {
                throw new ArgumentException("Invalid context type.", "context");
            }
            if (previouseDate != DateTime.Today)
            {
                previouseSequential = 0;
                previouseDate = DateTime.Today;
            }
            return c.CustomerCode + DateTime.Today.ToString("yyMMdd") +
                   (++previouseSequential).ToString("X").PadLeft(4, '0');
        }

        #endregion
    }
}
